﻿using UnityEngine;
using System.Collections;
using System.IO;

public class ScreenshotCapturer : MonoBehaviour {

	public ScreenshotData screenShotData;

	// Use this for initialization
	void Start () {
		screenShotData = GameObject.Find("DataManager").GetComponent<ScreenshotData>();
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	IEnumerator UploadPNG()
	{
		yield return new WaitForEndOfFrame();

		int w = Screen.width, h = Screen.height;
		Texture2D tex = new Texture2D(w, h, TextureFormat.RGB24, false);
		tex.ReadPixels(new Rect(0, 0, w, h), 0, 0);
		tex.Apply();
		Debug.Log(tex.ToString());
		
		//scrShotInTex = new Texture2D(w, h, TextureFormat.RGB24, false);
		screenShotData.setScreenshotInTexture(new Texture2D(w, h, TextureFormat.RGB24, false));
		//scrShotInTex.ReadPixels(new Rect(0, 0, w, h), 0, 0);
		screenShotData.getScreenshotInTexture().ReadPixels(new Rect(0, 0, w, h), 0, 0);
		//scrShotInTex.Apply();
		screenShotData.getScreenshotInTexture().Apply();
		
		//screenshotInBytes = tex.EncodeToJPG();
		screenShotData.setScreenshotInBytes(tex.EncodeToJPG());
		Debug.Log(screenShotData.getScreenshotInBytes().Length);
		//GameObject.Find("UIManager").GetComponent<FileSaver>().screenShot = tex.EncodeToJPG();

		//Run only once
		StopCoroutine("UploadPNG");
	}

	void UploadPNGNoEnum()
	{
		int w = Screen.width, h = Screen.height;
		Texture2D tex = new Texture2D(w, h, TextureFormat.RGB24, false);
		tex.ReadPixels(new Rect(0, 0, w, h), 0, 0);
		tex.Apply();
		Debug.Log(tex.ToString());

		//scrShotInTex = new Texture2D(w, h, TextureFormat.RGB24, false);
		screenShotData.setScreenshotInTexture(new Texture2D(w, h, TextureFormat.RGB24, false));
		//scrShotInTex.ReadPixels(new Rect(0, 0, w, h), 0, 0);
		screenShotData.getScreenshotInTexture().ReadPixels(new Rect(0, 0, w, h), 0, 0);
		//scrShotInTex.Apply();
		screenShotData.getScreenshotInTexture().Apply();

		//screenshotInBytes = tex.EncodeToJPG();
		screenShotData.setScreenshotInBytes(tex.EncodeToJPG());
		Debug.Log(screenShotData.getScreenshotInBytes().ToString());
		//GameObject.Find("UIManager").GetComponent<FileSaver>().screenShot = tex.EncodeToJPG();
	}

	public void toScreenshot()
	{
		//looks for the camera that renders the UI
		Camera UICamera = GameObject.Find("UI Root (2D)").GetComponentInChildren<Camera>();
		int curCullMask = UICamera.cullingMask;
		//converts UI Camera to render nothing
		UICamera.cullingMask = 0;
		//take a screenshot
		StartCoroutine(UploadPNG());
		//revert back to normal
		UICamera.cullingMask = curCullMask;
		Debug.Log("Screenshot taken!");
	}
}
